package util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "EncodingFilter"
        ,urlPatterns = "/*")
public class EncodingFilter implements javax.servlet.Filter {
    private String encode = "UTF-8";
    private String content = "application/json;charset=UTF-8";
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp
            , FilterChain chain) throws ServletException, IOException {
        // 1.强制转换
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // 2.操作
        if (request.getMethod().contains("Delete"))
        {
            response.setContentType(content);
        } else {
            request.setCharacterEncoding(encode);
            response.setContentType(content);
        }

        //3.放行
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
    }

}
